//
//  CustomTabBar.m
//  futureLive
//
//  Created by zhoubiwen on 15/11/16.
//  Copyright © 2015年 ZHOU_LI_SUN. All rights reserved.
//

#import "CustomTabBar.h"


@interface CustomTabBar ()

@property (nonatomic, weak) UIButton *selectedButton;

@end

@implementation CustomTabBar



- (void)addButtonWithImage:(UIImage *)image selectedImage:(UIImage *)selectedImage {
    
    UIButton *btn = [[UIButton alloc]init];
    [btn setImage:image forState:UIControlStateNormal];
    [btn setImage:image forState:UIControlStateSelected];
    [self addSubview:btn];
    [btn addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpOutside];
    
}

- (void)clickButton:(UIButton *)button {

    //1.先将之前选中的按钮设置为未选中
    self.selectedButton.selected = NO;
    //2.再将当前按钮设置为选中
    button.selected = YES;
    //3.最后把当前按钮赋值为之前选中的按钮
    self.selectedButton = button;
    
    //却换视图控制器的事情,应该交给controller来做
    //最好这样写, 先判断该代理方法是否实现
    if ([self.delegate respondsToSelector:@selector(tabBar:selectedFrom:to:)]) {
        [self.delegate tabBar:self selectedFrom:self.selectedButton.tag to:button.tag];
    }
    
    //4.跳转到相应的视图控制器. (通过selectIndex参数来设置选中了那个控制器)
    self.selectedIndex = button.tag;

}
- (void)setSelectedIndex:(NSUInteger)selectedIndex {
    
    if (_selectedIndex != selectedIndex) {
        
        
        _selectedIndex = selectedIndex;
        
     }

}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    int count = (int)self.subviews.count;
    for (int i = 0; i < count; i++) {
        
        //取得按钮
        UIButton *btn = self.subviews[i];
        
        btn.tag = i; //设置按钮的标记, 方便来索引当前的按钮,并跳转到相应的视图
        
        CGFloat x = i * self.bounds.size.width / count;
        CGFloat y = 0;
        CGFloat width = self.bounds.size.width / count;
        CGFloat height = self.bounds.size.height;
        btn.frame = CGRectMake(x, y, width, height);
        
    }

}


@end
